use axum::{http::StatusCode, Json};
use embd::Embd;
use lazy_static::lazy_static;
use log::info;
use vsse::{content::Content, engine::Engine};

#[cfg(feature = "use_cache")]
use crate::cache::CacheStore;
use crate::{
    api::data::{OutputItem, A, Q},
    statics::{CONTENT_STORE, DEFAULT_SEARCH_CONFIG, SERVER_CONFIG, SIMPLE_ENGINE},
};

#[cfg(feature = "use_cache")]
lazy_static! {
    static ref POST_DATA_CACHE: CacheStore<Q, A> =
        { CacheStore::<Q, A>::new(SERVER_CONFIG.cache_dur) };
}

pub(crate) async fn post_data(Json(posted): Json<Q>) -> (StatusCode, Json<A>) {
    let sentence = &posted.input;
    let serach_config = posted.search_config.as_ref().unwrap_or(&DEFAULT_SEARCH_CONFIG);

    info!("Connection Dected. Querying : {}", sentence);
    #[cfg(feature = "use_cache")]
    if let Some(some) = POST_DATA_CACHE.get(&posted).await {
        info!("Use cache for query : {}", sentence);
        return (StatusCode::OK, Json(some));
    }
    let result = SIMPLE_ENGINE
        .search(&sentence, &CONTENT_STORE, serach_config)
        .await
        .unwrap();
    info!("Successfully get results.");
    let output = result.contents.into_iter().map(|item| OutputItem::from_contentcollection_item(item)).collect::<Vec<_>>();
    let answer = A::new(sentence.to_owned(), output);
    (StatusCode::OK, Json(answer))
}
